class CreateUsersWallets < ActiveRecord::Migration
  def self.up
    create_table :user_wallets, :id => false do |t|
      t.integer :user_id, :null => false
      t.integer :wallet_id, :null => false
      t.integer :user_type, :default => 1 # owner
      t.boolean :is_default_wallet, :default => false
    end

    add_index :user_wallets, [:user_id, :wallet_id], :unique => true

    Wallet.all.each do |w|
      UserWallet.create!(:wallet_id => w.id, :is_default_wallet => w.is_default, :user_id => w.user_id)
    end

    remove_column(:wallets, :user_id, :is_default)
  end

  def self.down
    add_column :wallets, :user_id, :integer
    add_column :wallets, :is_default, :boolean, :default => false

    UserWallet.all.each do |uw|
      Wallet.find_by_id(uw.wallet_id).update(:is_default => uw.is_default_wallet, :user_id => w.user_id)
    end

    drop_table :users_wallets
  end
end
